<!--库存预警-->
<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" style="text-align: left;">
      <el-form-item label="货品" prop="procname">
        <el-input placeholder="请输入货品名称" v-model="searchForm.procname"></el-input>
      </el-form-item>
      <el-form-item label="货品类型" prop="proctype">
            <el-tree-select v-model="searchForm.proctype" :data="types"
                    :props="{
                        value: 'type_id',
                        label: 'type_name',
                        children: 'children'
                    }"
                    placeholder="请选择"
                    style="width: 200px"
                    check-strictly
                    default-expand-all/>
        </el-form-item>
      <el-form-item label="上下限" prop="limitType">
        <el-select v-model="searchForm.limitType" placeholder="请选择" style="width:180px">
          <el-option label="低于下限" value="low" />
          <el-option label="高于上限" value="high" />
        </el-select>
      </el-form-item>
      <el-form-item label="当前库存" prop="stocknum">
                <div style="display: flex; align-items: center; ">
                        <el-input placeholder="请输入"  v-model="searchForm.startnum"/>
                        <span style="margin: 0 8px;">~</span>
                        <el-input placeholder="请输入"  v-model="searchForm.endnum"/>
                </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <div style="text-align: left;">
        <el-button @click="Export">导出</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" style="margin-top: 10px;" @selection-change="handleSelectionChange"
              :row-class-name="tableRowClassName">
      <el-table-column type="selection" fixed="left"></el-table-column>
      <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
      <el-table-column prop="proc_code" label="货品编号" width="200" fixed="left"></el-table-column>
      <el-table-column prop="proc_name" label="货品名称" width="200" fixed="left"></el-table-column>
      <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
      <el-table-column prop="proc_unit" label="单位" width="100"></el-table-column>
      <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
      <el-table-column prop="wh_name" label="所属仓库" width="100"></el-table-column>
      <el-table-column prop="proc_inventory" label="当前库存" width="120" align="center">
        <template #default="scope">
          <span :style="getInventoryStyle(scope.row)">
            {{ scope.row.proc_inventory }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="proc_min" label="库存下限"></el-table-column>
      <el-table-column prop="proc_max" label="库存上限"></el-table-column>
      <el-table-column prop="low_percent" label="低于下限%" width="120" align="center">
        <template #default="scope">
          <span v-if="parseFloat(scope.row.low_percent) > 0"
                :style="{
                  color: '#ff4d4f',
                  fontWeight: 'bold',
                  backgroundColor: '#fff2f0',
                  padding: '2px 6px',
                  borderRadius: '4px'
                }">
            {{ scope.row.low_percent }}%
          </span>
          <span v-else style="color: #52c41a;">正常</span>
        </template>
      </el-table-column>
      <el-table-column prop="high_percent" label="高于上限%" width="120" align="center">
        <template #default="scope">
          <span v-if="parseFloat(scope.row.high_percent) > 0"
                :style="{
                  color: '#fa8c16',
                  fontWeight: 'bold',
                  backgroundColor: '#fff7e6',
                  padding: '2px 6px',
                  borderRadius: '4px'
                }">
            {{ scope.row.high_percent }}%
          </span>
          <span v-else style="color: #52c41a;">正常</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="warning_time" label="预警时间" width="180"></el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :page-size="pageSize"
      :current-page="currentPage"
      layout="prev, pager, next, jumper"
      :total="total"
      @current-change="handlePageChange"
      style="float:right;margin-top:20px"
    />
  </div>
</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
  setup() {
        // 搜索表单
        const searchForm = reactive({
            procname: '',
            proctype: '',
            limitType: '',
            stocknum: '',
            startnum:'',
            endnum:''
        });
        const searchFormRef = ref(null);

        //查询所有货品类型绑定到下拉框
        const types=ref([]);
        function AllType(){
            http.get("/ProductType/GetAllProductTypes")
            .then(res=>{
                types.value=convertToTree(res.data);
            }).catch(err=>{
                console.log(err);
            })
        }

         // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
         function convertToTree(data) {
            // 先创建一个以 type_id 为键的映射表，方便快速查找节点
            const map = {};
            data.forEach(item => {
                map[item.type_id] = { ...item, children: [] };
            });
            const tree = [];
            data.forEach(item => {
                const node = map[item.type_id];
                if (item.type_pid === 0) {
                    // 如果是顶层节点，直接添加到树中
                    tree.push(node);
                } else {
                    const parent = map[item.type_pid];
                    if (parent) {
                        // 如果父节点存在，将当前节点添加到父节点的 children 中
                        parent.children.push(node);
                    } else {
                        // 如果父节点不存在，将其作为顶层节点添加到树中
                        tree.push(node);
                    }
                }
            });
            return tree;
        }

    // 表格数据
    const tableData = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);

    // 查询方法
    const search = () => {
      fetchData();
    };
    // 重置方法
    const resetSearch = () => {
      searchForm.startnum = '';
      searchForm.endnum = '';
      searchFormRef.value?.resetFields();
      fetchData();
    };
    // 分页切换
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchData();
    };

    // 获取数据
    const fetchData = () => {
      http.get('/StockWarning/GetStockWarning', {
        params: {
          name:searchForm.procname,
          type:searchForm.proctype,
          warning:searchForm.limitType,
          startnum:searchForm.startnum,
          endnum:searchForm.endnum,
          CurrentPage:currentPage.value
        }
      }).then(res => {
        tableData.value = res.data.list;
        //转换时间并计算百分比
        tableData.value.forEach(item => {
            item.warning_time = formatDateTime(new Date(item.warning_time));

            // 计算低于库存下限的百分比
            if (item.proc_min && item.proc_min > 0) {
                if (item.proc_inventory < item.proc_min) {
                    // 当前库存低于下限时，计算低于下限的百分比
                    item.low_percent = ((item.proc_min - item.proc_inventory) / item.proc_min * 100).toFixed(2);
                } else {
                    item.low_percent = '0.00';
                }
            } else {
                item.low_percent = '0.00';
            }

            // 计算高于库存上限的百分比
            if (item.proc_max && item.proc_max > 0) {
                if (item.proc_inventory > item.proc_max) {
                    // 当前库存高于上限时，计算高于上限的百分比
                    item.high_percent = ((item.proc_inventory - item.proc_max) / item.proc_max * 100).toFixed(2);
                } else {
                    item.high_percent = '0.00';
                }
            } else {
                item.high_percent = '0.00';
            }
        });
        total.value = res.data.rows;
      }).catch(err => {
        console.log(err.data);
      });
    };

    //刷新
    function Refresh(){
      http.get('/StockWarning/Refresh',{
        params:{
          name:searchForm.procname,
          type:searchForm.proctype,
          warning:searchForm.limitType,
          startnum:searchForm.startnum,
          endnum:searchForm.endnum,
          CurrentPage:currentPage.value
        }
      }).then(() => {
        ElMessage.success("刷新成功！");
        fetchData();
      }).catch(err => {
        console.log(err.data);
      });
    }


    //选中的数据
    const selectdata = ref([]);
    const handleSelectionChange = (val) => {
      selectdata.value = val;
    };
    //导出
    function Export(){
      if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "序号": row.sw_id,
                "货品编号": row.proc_code,
                "货品名称": row.proc_name,
                "货品类型": row.type_name,
                "规格型号": row.proc_model,
                "单位": row.proc_primary_unit,
                "仓库名称": row.wh_name,
                "当前库存": row.proc_inventory,
                "库存下限": row.proc_min,
                "库存上限": row.proc_max,
                "低于下限百分比": row.low_percent,
                "高于上限百分比": row.high_percent,
                "预警时间": row.warning_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "预警信息");
            // 导出并下载
            XLSX.writeFile(wb, `预警信息${new Date().toLocaleDateString()}.xlsx`);
    }

    onMounted(() => {
      AllType();
      fetchData();
    });

    // 时间转换
    function formatDateTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }

    // 根据库存状态设置样式
    function getInventoryStyle(row) {
        const inventory = parseFloat(row.proc_inventory) || 0;
        const minStock = parseFloat(row.proc_min) || 0;
        const maxStock = parseFloat(row.proc_max) || 0;

        if (minStock > 0 && inventory < minStock) {
            // 库存不足 - 红色
            return {
                color: '#ff4d4f',
                fontWeight: 'bold',
                backgroundColor: '#fff2f0',
                padding: '2px 6px',
                borderRadius: '4px'
            };
        } else if (maxStock > 0 && inventory > maxStock) {
            // 库存过量 - 橙色
            return {
                color: '#fa8c16',
                fontWeight: 'bold',
                backgroundColor: '#fff7e6',
                padding: '2px 6px',
                borderRadius: '4px'
            };
        } else {
            // 正常库存 - 绿色
            return {
                color: '#52c41a',
                fontWeight: 'normal'
            };
        }
    }

    // 表格行样式
    function tableRowClassName({ row }) {
        const inventory = parseFloat(row.proc_inventory) || 0;
        const minStock = parseFloat(row.proc_min) || 0;
        const maxStock = parseFloat(row.proc_max) || 0;

        if (minStock > 0 && inventory < minStock) {
            return 'warning-row';
        } else if (maxStock > 0 && inventory > maxStock) {
            return 'excess-row';
        }
        return '';
    }

    return {
      searchForm,
      searchFormRef,
      types,
      tableData,
      total,
      pageSize,
      currentPage,
      search,
      resetSearch,
      handlePageChange,
      Refresh,
      Export,
      handleSelectionChange,
      selectdata,
      getInventoryStyle,
      tableRowClassName
    };
  }
};
</script>

<style scoped>
/* 预警状态样式 */
.warning-text {
  color: #ff4d4f;
  font-weight: bold;
}

.normal-text {
  color: #52c41a;
}

.excess-text {
  color: #fa8c16;
  font-weight: bold;
}

/* 表格行样式 */
:deep(.el-table .warning-row) {
  background: #fff2f0;
}

:deep(.el-table .excess-row) {
  background: #fff7e6;
}
</style>